//class Solution {
//public:
//    vector<vector<int>> generateMatrix(int n) {
//        int left = 0, right = n - 1, top = 0, bottom = n - 1;
//        vector<vector<int>> ret(n, vector<int>(n));
//        int ans = 1;
//        while (left <= right && top <= bottom)
//        {
//            for (int i = left; i <= right; i++)
//                ret[top][i] = ans++;
//            for (int i = top + 1; i < bottom; i++)
//                ret[i][right] = ans++;
//            if (top < bottom)
//            {
//                for (int i = right; i > left; i--)
//                    ret[bottom][i] = ans++;
//                for (int i = bottom; i > top; i--)
//                    ret[i][left] = ans++;
//            }
//            left++, right--, top++, bottom--;
//        }
//        return ret;
//    }
//};



class Solution {
public:
    int findUnsortedSubarray(vector<int>& nums) {
        int n = nums.size() - 1;
        int maxn = INT_MIN, right = -1;
        int minn = INT_MAX, left = -1;
        for (int i = 0; i <= n; i++)
        {
            if (nums[i] < maxn) right = i;
            else maxn = nums[i];
            if (nums[n - i] > minn) left = n - i;
            else minn = nums[n - i];
        }
        return (right == -1) ? 0 : right - left + 1;
    }
};
